import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { UserDataService } from '../../providers/service/user-data.service';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { Network } from '@ionic-native/network';
import { DialogProvider } from '../../providers/dialog/dialog';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';

/**
 * Generated class for the LogPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-log',
  templateUrl: 'log.html',
})
export class LogPage {

	public loginInfo = {
		UserName: '',
		PassWord: '',
		isAutomaticLogon: false
  };
  
  // 登录信息
	userInfo: user_info = new user_info();

  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    public userData: UserDataService,
    public user: UserInfoProvider,
    private network: Network,
    public http: HttpProvider,
    public toastCtrl: ToastController,
    public dialog: DialogProvider,
    public storage: StorageProvider,
  ) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LogPage');
    this.login();
  }

  async login() {
    let a = await this.userData.find((user) => user.key !== '')

		if (a.length > 0) {
			this.loginInfo.UserName = a[0]['phone'];
			this.loginInfo.PassWord = a[0]['password'];
			this.loginInfo.isAutomaticLogon = a[0]['isAutomaticLogon'];
			this.userInfo = a[0];
		}

		var params = {
			username: this.loginInfo.UserName,
			password: this.loginInfo.PassWord,
			isAutomaticLogon: this.loginInfo.isAutomaticLogon,
		};
		/*调用接口的方式,这种写法接受参数需要json的格式*/
		if (this.network.type === 'none' || this.network.type === '2g') {
			let a = await this.userData.find((user) => (user.key !== ''));
			if (a[0].password === params.password && a[0].phone === params.username) {
				this.user.setuserInfo(this.userInfo);
				this.navCtrl.push('TabsPage');
			} else { 
        this.dialog.showToast('提示', '当前无网络只能登陆上一次登陆的用户'); 
      }

			return;
		}
		await this.http.postJson('', 'users/member/login', { 'phone': params.username, 'password': params.password }, '')
			.then(res => {
				console.log(res);
				if (res['status'] == 200) {
					//this.dialog.showAlert('您好'+res['data']['nickname'], res['message']);		
					this.http.login_stuta = 1;
					res['data']['password'] = params.password;
					res['data']['isAutomaticLogon'] = params.isAutomaticLogon;
					// this.storage.saveStorage("login_info", res['data']);
					this.userInfo = res['data'];
					this.user.setuserInfo(this.userInfo);
					this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
					this.getdictionary();
					this.navCtrl.push('TabsPage');
				} else {
          this.navCtrl.push('LoginPage');
					this.toastCtrl.create({
						message: res['message'],
						duration: 2000,
						position: 'top'
					}).present();
				}
			});
  }

  getdictionary() {
		this.http.postJson('', 'aindex/dictionary/index',
			{
				select: "m.D_GROUP",
				joinWith: "group", "groupby": "D_GROUP", "indexBy": "D_GROUP", "limit": 0,
				where: ["<>", "s_dictionary.D_STATE", 0]
			}, '')
			.then(res => {
				if (res['status'] == 200) {
					this.storage.saveStorage("dictionary", JSON.stringify(res['data']));
				}
			});
	}

}


export class user_info {
	member_id: any;
	nickname: any;
	phone: any;
	balance: any;
	local_balance: any;
	member_state: any;
	created_at: any;
	updated_at: any;
	cuser_id: any;
	uuser_id: any;
	is_del: any;
	password: any;
	file_type_id: any;
	access_token: any;
	isAutomaticLogon: any;
}